package com.dc.base.exception;

import com.dc.common.constants.ConstantsCommon;
import com.dc.common.model.BaseModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //系统异常统一处理
    @ExceptionHandler({Exception.class})
    public BaseModel exception(Exception ex) {

        //获取到错误信息
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //将错误信息记录到日志
        logger.error("系统异常发生！！！" + "\n=====================系统异常start=====================\n"+ ret + "=====================系统异常end=====================\n");

        //组装返回页面的json数据
        BaseModel baseModel = new BaseModel();
        baseModel.setCode(-1);
        baseModel.setMessage("系统异常,请联系管理员");
        return baseModel;
    }

    //业务异常统一处理
    @ExceptionHandler({BusinessException.class})
    public BaseModel businessException(BusinessException ex) {
        BaseModel baseModel = new BaseModel();
        baseModel.setCode(ex.getCode());
        baseModel.setMessage(ex.getMessage());
        return baseModel;
    }


}